package org.wishwork.api.base.shop;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.token.get.ResponseToken;
import org.wishwork.cache.DefaultMemoryCacheOperator;
import org.wishwork.constant.Constants;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: WangYX
 * @create: 2022-04-02 15:06
 * @Version: 1.0.0
 **/

public class ShopApi extends Api<List<ShopResponse>, ShopRequest> {

    private static final Logger log = LoggerFactory.getLogger(ShopApi.class);

    private Context context;

    public ShopApi(Context context) {
        this.context = context;
    }

    /**
     * 查询店铺
     *
     * @param shopRequest
     * @return
     * @throws IOException
     */
    @Override
    protected String query(ShopRequest shopRequest) throws Exception {

        ResponseToken token = (ResponseToken) DefaultMemoryCacheOperator.instance().get(Constants.TOKEN);

        String url = "/open/shops/query";
        //请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("page_index", shopRequest.getPageIndex());
        params.put("page_size", shopRequest.getPageSize());
        if (!StrUtil.isEmpty(shopRequest.getNicks())) {
            String[] split = shopRequest.getNicks().split(",");
            params.put("nicks", split);
        }

        String biz = JSON.toJSONString(params);
        //发送请求
        String result = HttpHelper.sendRequest(token.getAccessToken(), biz, url);
        return result;
    }

    /**
     * 店铺业务处理
     *
     * @param data 聚水潭返回的json数据
     * @return shopRequest 请求对象
     * @throws Exception
     */
    @Override
    protected List<ShopResponse> process(JSONObject data, ShopRequest shopRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<ShopResponse> shopResponses = datas.toJavaList(ShopResponse.class);
        //判断是否还有下一个
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer index = shopRequest.getPageIndex();
            ShopRequest build = shopRequest.toBuilder().pageIndex(++index).build();
            List<ShopResponse> result = business(build);
            shopResponses.addAll(result);
        }
        return shopResponses;
    }


}
